﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TravelingWebApp.Models;
using TravelingWebApp.Repositories;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using TravelingWebApp.Data;

namespace TravelingWebApp.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ContentController : Controller
    {
        private IScenaryRepositories _repo;
        private TravelingContext _context;
        private readonly IHostingEnvironment _hostingEnvironment;

        public ContentController(IScenaryRepositories repo, TravelingContext context, IHostingEnvironment hosting)
        {
            _repo = repo;
            _context = context;
            _hostingEnvironment = hosting;
        }

        // ================== 景点查看 ================
        [HttpGet]
        [Route("GetAllScenaries")]
        public ActionResult<JsonResult> GetAllScenaries()
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(Json(new { msg = "Model Invalid" }));
            }
            return Json(_repo.GetScenaries());
        }

        [HttpGet]
        [Route("GetAllScenariesStruct")]
        public ActionResult<JsonResult> GetAllScenariesStruct()
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(Json(new { msg = "Model Invalid" }));
            }
            //获取所有地市并去重
            var spots = from scenary in _context.DbScenaries
                        select scenary.City;
            var spots_dist = spots.Distinct().ToList();

            //按照地市把景点分组并打包
            var result = new List<object>();
            foreach (var value in spots_dist)
            {
                var children = from scenary in _context.DbScenaries
                               where scenary.City == value
                               select new { label = scenary.Spot, value = scenary.Id };
                result.Add(new { label = value, value, children });
            }
            return Json(new { spot = result });
        }

        [HttpGet]
        [Route("GetScenary")]
        public async Task<ActionResult<JsonResult>> GetScenary(string id)
        {
            try
            {
                // URL 传的就是字符串
                var scenary = await _context.DbScenaries.FindAsync(id);
                if (scenary == null)
                {
                    return BadRequest(Json(new { msg = "Invalid id" + id }));
                }
                return Ok(Json(scenary));
            }
            catch (Exception e)
            {
                return BadRequest(Json(new { msg = "Invalid id" + id }));
            }

        }

        // =================== 公告获取 ===================
        [HttpGet]
        [Route("GetAllAnnouncements")]
        public ActionResult<string> GetAllAnnouncements()
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(Json(new { msg = "Model Invalid" }));
            }
            return Json(_context.DbAnoucements.ToList());
        }

        [HttpGet]
        [Route("GetAnnouncement")]
        public async Task<ActionResult<string>> GetAnnouncement(string id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(Json(new { msg = "Model Invalid" }));
            }
            var announcement = await _context.DbAnoucements.FindAsync(id);
            if (announcement == null)
            {
                return BadRequest(Json(new { msg = "Invalid id" + id }));
            }
            return Ok(Json(announcement));
        }

        // =================== 评论获取 ===================
        [HttpGet]
        [Route("GetAllComments")]
        public ActionResult<IEnumerable<Comment>> GetAllComments()
        {
            return Json(_context.DbComments.ToList());
        }

        [HttpGet]
        [Route("GetComment")]
        public async Task<ActionResult<Comment>> GetComment(string id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(Json(new { msg = "Model Invalid" }));
            }
            var comment = await _context.DbComments.FindAsync(id);
            if (comment == null)
            {
                return BadRequest(Json(new { msg = "invalid id" }));
            }

            return Json(comment);
        }


        // =================== 导游获取 ====================
        [HttpGet]
        [Route("GetAllGuides")]
        public ActionResult<string> GetAllGuides()
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(Json(new { msg = "Model Invalid" }));
            }
            return Json(_context.DbGuides.ToList());
        }

        [HttpGet]
        [Route("GetGuide")]
        public async Task<ActionResult<string>> GetGuide(string id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(Json(new { msg = "Model Invalid" }));
            }
            var guide = await _context.DbGuides.FindAsync(id);
            if (guide == null)
            {
                return BadRequest(Json(new { msg = "Invalid id" + id }));
            }
            return Ok(Json(guide));
        }

        // ================== 订单查询 =========================
        [HttpGet]
        [Route("GetAllBills")]
        public ActionResult<IEnumerable<Comment>> GetAllBills()
        {
            return Json(_context.DbBills.ToList());
        }

        [HttpGet]
        [Route("GetBills")]
        public async Task<ActionResult<Comment>> GetBill(string id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(Json(new { msg = "Model Invalid" }));
            }
            var bill = await _context.DbBills.FindAsync(id);
            if (bill == null)
            {
                return BadRequest(Json(new { msg = "invalid id" }));
            }

            return Json(bill);
        }

        // ================ 路线生成（全排列） =============
        //private static void Swap(ref string a, ref string b)
        //{
        //    string temp = a;
        //    a = b;
        //    b = a;
        //}
        //
        //private static void Perm(string[] list, int begin, int end, ref List<string> res)
        //{
        //    if (begin == end)
        //    {
        //        string str = "";
        //        for (int i = 0; i <= begin; i++)
        //        {
        //            str += "=>" + list[i];
        //            Console.WriteLine(str);
        //        }
        //        res.Add(str);
        //    }
        //    else
        //        for (int i = begin; i <= end; i++)
        //        {
        //            Swap(ref list[i], ref list[begin]);
        //            Perm(list, begin + 1, end, ref res);
        //            Swap(ref list[i], ref list[begin]);
        //        }
        //}

        private static void SuperLazy(string[] list, ref List<string> res)
        {
            string str;
            for(int i=0; i<list.Count(); i++)
            {
                str = "";
                for(int j=i; j<i+ list.Count(); j++)
                {
                    str += "=>" + list[j % list.Count()];
                }
                res.Add(str);
            }
        }

        [HttpGet]
        [Route("GetRoutes")]
        public ActionResult<string> GenerateRoutes(string City)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(Json(new { msg = "Model Invalid" }));
            }

            var Names = (from scenary in _context.DbScenaries
                         where scenary.City == City
                         select scenary.Name).ToArray();
            var result = new List<string>();

            //Perm(Names, 0, Names.Count()-1, ref result);
            SuperLazy(Names, ref result);

            return Ok(Json(result));
        }
    }


    // =================== 路线获取 ====================
    //[HttpGet]
    //[Route("GetAllRoutes")]
    //public ActionResult<string> GetAllRoutes()
    //{
    //    return JsonConvert.SerializeObject(_repo.GetScenaries());
    //}
    //
    //[HttpGet]
    //[Route("GetRoute")]
    //public async Task<ActionResult<string>> GetRoutes(string id)
    //{
    //    var scenary = await _context.DbScenaries.FindAsync();
    //    if (scenary == null)
    //    {
    //        return NotFound();
    //    }
    //    return Ok(JsonConvert.SerializeObject(scenary));
    //    }
    
}
